package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.google.common.cache.CacheBuilder;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.BrandAuditEnum;
import com.zbkj.crmeb.front.vo.BrandVo;
import com.zbkj.crmeb.store.dao.StoreBrandDao;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dto.StoreBrandDTO;
import com.zbkj.crmeb.store.model.ChannelStoreBrandConfig;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreBrandAudit;
import com.zbkj.crmeb.store.request.StoreBrandRequest;
import com.zbkj.crmeb.store.response.ListByCateResponse;
import com.zbkj.crmeb.store.response.StoreBrandResponse;
import com.zbkj.crmeb.store.service.ChannelStoreBrandConfigService;
import com.zbkj.crmeb.store.service.StoreBrandAuditService;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.google.common.cache.Cache;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StoreBrandServiceImpl extends ServiceImpl<StoreBrandDao, StoreBrand> implements StoreBrandService {

    private static final Logger logger = LoggerFactory.getLogger(StoreBrandServiceImpl.class);
    @Resource
    private StoreBrandDao storeBrandDao;
    @Autowired
    ChannelStoreBrandConfigService channelStoreBrandConfigService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private StoreProductServiceImpl storeProductService;
    @Autowired
    private StoreBrandAuditService storeBrandAuditService;
    @Autowired
    private SupplierService supplierService;

    @Resource
    private StoreProductDao storeProductDAO;

    // 声明一个 Guava Cache 实例用于缓存品牌数据
//    private Cache<String, List<Integer>> cacheBrandIds;

    public static final String REDIS_KEY_BRANDLIST = "rds_key_brand_list";

    /*public StoreBrandServiceImpl() {
        // 使用 Guava CacheBuilder 来创建一个缓存实例
        cacheBrandIds = CacheBuilder.newBuilder()
                .expireAfterWrite(12, TimeUnit.HOURS) // 设置缓存过期时间为12小时
                .build();
    }*/

    @Override
    public StoreBrand getByBrandId(Integer brandId) {
        return this.getOne(Wrappers.<StoreBrand>lambdaQuery().eq(StoreBrand::getId, brandId));
    }

    @Override
    public Map<Integer, String> getBrandNameMap(List<Integer> list) {
        List<StoreBrand> brandList = this.list(Wrappers.<StoreBrand>lambdaQuery().in(StoreBrand::getId, list));
        return brandList.stream().collect(Collectors.toMap(StoreBrand::getId, StoreBrand::getEnName));
    }

    /**
     * 处理品牌-在线商品数量
     * true +1, false -1
     */
    @Override
    public void showProductCount(Integer brandId, Boolean flag) {

        if (null != brandId) {
            //获取原来的product_count
            StoreBrand storeBrand = this.getByBrandId(brandId);
            if (ObjectUtils.isNull(storeBrand)) {
                return;
            }
            //设置品牌-字段product_count
            Integer newProductCount = storeBrand.getProductCount();
            if (flag) {
                newProductCount = newProductCount + 1;
            } else if (newProductCount > 0) {
                newProductCount = newProductCount - 1;
            }
            this.update(Wrappers.<StoreBrand>lambdaUpdate().set(StoreBrand::getProductCount, newProductCount).eq(StoreBrand::getId, brandId));
        }
    }

    /**
     * 根据品牌id获取品牌名称
     *
     * @param brandName
     * @return
     */
    @Override
    public List<Integer> brandIdlist(String brandName) {
        return storeBrandDao.brandIdlist(brandName);
    }

    /**
     * 品牌名称
     *
     * @param brandId
     */
    @Override
    public String getBrandName(Integer brandId) {
        String brandName = "";
        if (null != brandId) {
            QueryWrapper<StoreBrand> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(StoreBrand::getEnName);
            queryWrapper.lambda().eq(StoreBrand::getId, brandId);
            List<StoreBrand> storeBrandList = storeBrandDao.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(storeBrandList)) {
                StoreBrand storeBrand = storeBrandList.get(0);
                if (ObjectUtils.isNotEmpty(storeBrand)) {
                    brandName = storeBrand.getEnName();
                }
            }
        }
        return brandName;
    }

    @Override
    public StoreBrand getBrandName(String brandName, Integer createUserId) {
        QueryWrapper<StoreBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StoreBrand::getEnName, brandName);
        queryWrapper.lambda().eq(StoreBrand::getIsDeleted, 0);
        queryWrapper.lambda().eq(StoreBrand::getCreateUserId, createUserId);
        queryWrapper.last("LIMIT 1");
        return getOne(queryWrapper);
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo<StoreBrandResponse> pageEntity(StoreBrandRequest request) {
        Page<Object> page = PageHelper.startPage(request.getPageNow(), request.getPageSize());
        List<StoreBrandResponse> storeBrandResponses = storeBrandDao.pageEntity(request);
        Map<Integer, String> createUserNameMap = new HashMap<>();

        for (StoreBrandResponse response : storeBrandResponses) {
            if (0 == response.getIdentityType()) continue;
            String userName = createUserNameMap.get(response.getCreateUserId());
            if (StrUtil.isEmpty(userName)) {
                if (1 == response.getIdentityType() || 2 == response.getIdentityType()) {
                    ChannelMerchant merchant = channelMerchantService.getById(response.getCreateUserId());
                    if (null != merchant) {
                        createUserNameMap.put(merchant.getId(), merchant.getChannelName());
                        userName = merchant.getChannelName();
                    }
                } /*else if (2 == response.getIdentityType()) {
                    Supplier supplier = supplierService.getById(response.getCreateUserId());
                    if (null != supplier) {
                        createUserNameMap.put(supplier.getId(), supplier.getSuppliersName());
                        userName = supplier.getSuppliersName();
                    }
                }*/
            }
            response.setCreateUserName(userName);
        }

        return CommonPage.copyPageInfo(page, storeBrandResponses);
    }

    /**
     * 主键查询
     */
    @Override
    public StoreBrandResponse getEntity(Integer id) {
        StoreBrandResponse storeBrandResponse = storeBrandDao.getEntity(id);

        return storeBrandResponse;
    }

    /**
     * 保存
     */
    @Override
    public Boolean saveEntity(StoreBrandDTO dto) {
        StoreBrand storeBrand = new StoreBrand();
        BeanUtil.copyProperties(dto, storeBrand);
        storeBrand.setCreateTime(new Date());
        storeBrand.setUpdateTime(new Date());
        int insert = storeBrandDao.insert(storeBrand);
        if (insert > 0 && Objects.nonNull(dto.getAuditId())) {
            storeBrandAuditService.update(Wrappers.<StoreBrandAudit>lambdaUpdate().set(StoreBrandAudit::getStatus, BrandAuditEnum.HAVE_BEEN_ADDED.getCode()).eq(StoreBrandAudit::getId, dto.getAuditId()));
        }
        return true;
    }

    /**
     * 修改
     */
    @Override
    public Boolean updateEntity(StoreBrandDTO dto) {
        StoreBrand storeBrand = new StoreBrand();
        BeanUtil.copyProperties(dto, storeBrand);
        storeBrand.setUpdateTime(new Date());

        storeBrandDao.updateById(storeBrand);
        return true;
    }

    @Override
    public List<StoreBrand> selectStoreBrandList(StoreBrandRequest request) {
        QueryWrapper<StoreBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StoreBrand::getIsDeleted, false);
        queryWrapper.lambda().eq(StoreBrand::getType, 1);
        queryWrapper.lambda().eq(StoreBrand::getStatus, true);
        if (CollectionUtils.isEmpty(request.getIds())) {
            queryWrapper.lambda().eq(null != request.getIsAdvice(), StoreBrand::getIsAdvice, true);
        }
        queryWrapper.lambda().in(CollectionUtils.isNotEmpty(request.getIds()), StoreBrand::getId, request.getIds());

        return storeBrandDao.selectList(queryWrapper);
    }

    @Override
    public void updateList(List<Map<String, Object>> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            storeBrandDao.updateList(list);
        }
    }


    @Override
    public ListByCateResponse listByCate(Integer cateType, String cateId, Integer merId) {
        ListByCateResponse listByCateResponse = new ListByCateResponse();
        // 获取商户可见品牌
        List<Integer> merBrandIdList = storeProductService.getBrandsByMerId(merId, cateId);
        List<BrandVo> brandVoList = getBrandVos(merBrandIdList);
        listByCateResponse.setBrandList(brandVoList);
        //热门
        StoreBrandRequest storeBrandRequest = new StoreBrandRequest();
        storeBrandRequest.setStatus(true);
        List<ChannelStoreBrandConfig> brandConfigs = channelStoreBrandConfigService.list(Wrappers.lambdaQuery(ChannelStoreBrandConfig.class)
                .eq(ChannelStoreBrandConfig::getMerId, merId)
                .like(ChannelStoreBrandConfig::getCateHot, cateType)
                .orderByDesc(ChannelStoreBrandConfig::getHotTime));
        List<Integer> configIdList = brandConfigs.stream().map(ChannelStoreBrandConfig::getBrandId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(configIdList)) {
            configIdList.retainAll(merBrandIdList);
            configIdList.add(0);
            storeBrandRequest.setIds(configIdList);
            //分类热门品牌
            List<StoreBrandResponse> list = storeBrandDao.pageEntity(storeBrandRequest);
            List<BrandVo> voList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                list.sort(((o1, o2) -> {
                    int io1 = configIdList.indexOf(o1.getId());
                    int io2 = configIdList.indexOf(o2.getId());
                    return io1 - io2;
                }));
                voList = list.stream().map(brand -> new BrandVo(brand.getId(), brand.getEnName(), brand.getLetter(), brand.getLogo())).collect(Collectors.toList());
            }
            listByCateResponse.setHotList(voList);
        }

        // 品牌图片展示
        String isBrandImage = systemConfigService.getValueByKey(Constants.CONFIG_KEY_APP_BRAND_IMG_STATUS + merId);
        if (StringUtil.isEmpty(isBrandImage) || "0".equals(isBrandImage)) {
            listByCateResponse.setIsBrandImage(false);
        } else {
            listByCateResponse.setIsBrandImage(true);
        }

        return listByCateResponse;
    }

    public List<BrandVo> getBrandVos(List<Integer> merBrandIdList) {
        // 当前所有品牌
        List<StoreBrand> storeBrandList = list(Wrappers.lambdaQuery(StoreBrand.class).eq(StoreBrand::getStatus, 1).eq(StoreBrand::getType, 1).eq(StoreBrand::getIsDeleted, 0));
        List<StoreBrand> collect = storeBrandList.stream().filter(e -> merBrandIdList.contains(e.getId())).collect(Collectors.toList());
        List<BrandVo> brandVoList;
        if (CollectionUtils.isNotEmpty(collect)) {
            brandVoList = collect.stream().map(brand -> new BrandVo(brand.getId(), brand.getEnName(), brand.getLetter(), brand.getLogo()))
                    .sorted((x, y) -> {
                        String brandNameX = x.getName();
                        String brandNameY = y.getName();
                        //小写转大写
                        if (brandNameX.matches(".*?[a-z]+.*?")) {
                            brandNameX = brandNameX.toUpperCase();
                        }
                        if (brandNameY.matches(".*?[a-z]+.*?")) {
                            brandNameY = brandNameY.toUpperCase();
                        }
                        return brandNameX.compareTo(brandNameY);
                    }).collect(Collectors.toList());
        } else {
            brandVoList = new ArrayList<>();
        }
        return brandVoList;
    }

    @Override
    public List<Integer> getMerShowBrand(Integer merId,String from) {
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        String suppliersIds = channelMerchant.getSuppliersIds();
        JSONArray brandNames = JSONArray.parseArray(channelMerchant.getBrandIds());
        List<Integer> merBrandIdList = null;
        if (!brandNames.isEmpty()){
            return brandNames.toJavaList(Integer.class);
        }
        // 根据供应商查询品牌
        if(StringUtils.isNotBlank(suppliersIds) && !Objects.equals("[]",suppliersIds) && Objects.equals(from,"mer") && channelMerchant.getChannelType() != 3){
            List<Integer> supplierIdList = JSONArray.parseArray(suppliersIds).toJavaList(Integer.class);
            
            logger.info("{},关联供应商: {}",channelMerchant.getChannelName(),JSON.toJSON(supplierIdList));
            List<Integer> list = storeProductDAO.selectBrandIdsBySupplierIds(supplierIdList);
            // 把渠道商户自建的品牌追加到最后
            List<StoreBrand> selfBuiltBrandList = this.lambdaQuery().eq(StoreBrand::getCreateUserId, merId).list();
            if(CollectionUtils.isNotEmpty(selfBuiltBrandList)) {
                list.addAll(selfBuiltBrandList.stream().map(StoreBrand::getId).collect(Collectors.toList()));
            }
            if (CollectionUtils.isNotEmpty(list)){
                return list;
            }
        }else if (Objects.isNull(brandNames) || brandNames.isEmpty()) {
            logger.info("{},没有可展示的品牌和供应商",channelMerchant.getChannelName());
            //所有品牌
            merBrandIdList = list(Wrappers.lambdaQuery(StoreBrand.class).eq(StoreBrand::getStatus, 1).eq(StoreBrand::getType, 1).eq(StoreBrand::getIsDeleted, 0).select(StoreBrand::getId))
                    .stream().map(StoreBrand::getId).collect(Collectors.toList());
        }
        return merBrandIdList;
    }

    public List<BrandVo> clearBrandList(List<StoreBrandResponse> list) {
        List<BrandVo> voList;
        if (CollectionUtils.isNotEmpty(list)) {
            voList = list.stream().map(brand -> new BrandVo(brand.getId(), brand.getEnName(), brand.getLetter(), brand.getLogo()))
                    .sorted((x, y) -> {
                        String brandNameX = x.getName();
                        String brandNameY = y.getName();
                        //小写转大写
                        if (brandNameX.matches(".*?[a-z]+.*?")) {
                            brandNameX = brandNameX.toUpperCase();
                        }
                        if (brandNameY.matches(".*?[a-z]+.*?")) {
                            brandNameY = brandNameY.toUpperCase();
                        }
                        return brandNameX.compareTo(brandNameY);
                    }).collect(Collectors.toList());
        } else {
            voList = new ArrayList<>();
        }
        return voList;
    }

    @Override
    public PageInfo<StoreBrandResponse> getMerBrandList(StoreBrandRequest storeBrandRequest, Integer merId) {
        if (storeBrandRequest.getCateType() == null) {
            throw new CrmebException("分类推荐不能为空");
        }
        // 获取商户可见品牌
        List<Integer> merBrandIdList = getMerShowBrand(merId,"");
        storeBrandRequest.setStatus(true);
        // 获取商户配置项
        List<ChannelStoreBrandConfig> configs = channelStoreBrandConfigService.list(Wrappers.<ChannelStoreBrandConfig>lambdaQuery()
                .eq(ChannelStoreBrandConfig::getMerId, merId)
                .like(storeBrandRequest.getCateType() != 0, ChannelStoreBrandConfig::getCateHot, storeBrandRequest.getCateType())
                .eq(null != storeBrandRequest.getIsAdvice(), ChannelStoreBrandConfig::getIsAdvice, 1));
        Map<Integer, ChannelStoreBrandConfig> map = configs.stream().collect(Collectors.toMap(ChannelStoreBrandConfig::getBrandId, e -> e));
        Set<Integer> configIds = map.keySet();
        if (null != storeBrandRequest.getIsAdvice() || storeBrandRequest.getCateType() != 0) {
            merBrandIdList.retainAll(configIds);
        }
        merBrandIdList.add(0);
        storeBrandRequest.setIds(merBrandIdList);
        PageInfo<StoreBrandResponse> page = pageEntity(storeBrandRequest);
        for (StoreBrandResponse brand : page.getList()) {
            if (configIds.contains(brand.getId())) {
                brand.setIsAdvice(map.get(brand.getId()).getIsAdvice() ? 1 : 0);
                brand.setCateHotList(null != map.get(brand.getId()).getCateHot()
                        ? Stream.of(map.get(brand.getId()).getCateHot().split(",")).filter(StringUtils::isNotBlank).map(Integer::parseInt).collect(Collectors.toList())
                        : new ArrayList<>());
            } else {
                brand.setIsAdvice(0).setCateHotList(new ArrayList<>());
            }
        }
        return page;
    }

    @Override
    public List<BrandVo> listBrand(Integer merId) {
        // 获取商户可见品牌
        List<Integer> merBrandIdList = storeProductService.getBrandsByMerId(merId, null);
        return getBrandVos(merBrandIdList);
//        List<BrandVo> voList = (List<BrandVo>) redisUtil.get(REDIS_KEY_BRANDLIST);
//        if (CollectionUtils.isEmpty(voList)) {
//            //获取所有上架商品的品牌id
//            List<Integer> brandIdList = storeProductService.getAllStoreProductBrand();
//            List<StoreBrand> list = list(Wrappers.<StoreBrand>lambdaQuery()
//                    .eq(StoreBrand::getStatus, true)
//                    .eq(StoreBrand::getType, BrandTypeEnum.XUNWU)
//                    .in(StoreBrand::getId, brandIdList)
//                    .orderByAsc(StoreBrand::getLetter)
//            );
//            if (CollectionUtils.isNotEmpty(list)) {
//                voList = list.stream().map(brand -> new BrandVo(brand.getId(), brand.getEnName(), brand.getLetter()))
//                        .sorted((x, y) -> {
//                            String brandNameX = x.getName();
//                            String brandNameY = y.getName();
//                            //小写转大写
//                            if (brandNameX.matches(".*?[a-z]+.*?")){
//                                brandNameX = brandNameX.toUpperCase();
//                            }
//                            if (brandNameY.matches(".*?[a-z]+.*?")){
//                                brandNameY = brandNameY.toUpperCase();
//                            }
//                            return brandNameX.compareTo(brandNameY);
//                        }).collect(Collectors.toList());
//
//                redisUtil.set(REDIS_KEY_BRANDLIST, voList, ExpireTimeConstants.HALF_HOUR, TimeUnit.SECONDS);
//            } else {
//                voList = new ArrayList<>();
//            }
//        }
//        return voList;
    }

    @Override
    public List<BrandVo> listBrandByMerId(Integer merId) {
        // 获取商户可见品牌
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        JSONArray brandNames = JSONArray.parseArray(channelMerchant.getBrandIds());
        List<Integer> merBrandIdList;
        if (brandNames.isEmpty()) {
            //修改不显示所有品牌 2.24
            JSONArray suppliersIds = JSONArray.parseArray(channelMerchant.getSuppliersIds());

            //供应商是空的 获取供应商商品下面所有的品牌
            if (suppliersIds.isEmpty()) {
                //所有商品的品牌2.28
                merBrandIdList = storeProductService.getAllStoreProductBrand();
                //获取对应供应商商品的品牌 ok
            } else {
                merBrandIdList = storeProductService.getBrandsByMerId(merId, null);
            }
        } else {
            merBrandIdList = brandNames.toJavaList(Integer.class);
        }

        return getBrandVos(merBrandIdList);
//        return merBrandIdList;

//        List<Integer> merBrandIdList = getMerShowBrand(merId);
//        return getBrandVos(merBrandIdList);
//        List<BrandVo> voList = (List<BrandVo>) redisUtil.get(REDIS_KEY_BRANDLIST);
//        if (CollectionUtils.isEmpty(voList)) {
//            //获取所有上架商品的品牌id
//            List<Integer> brandIdList = storeProductService.getAllStoreProductBrand();
//            List<StoreBrand> list = list(Wrappers.<StoreBrand>lambdaQuery()
//                    .eq(StoreBrand::getStatus, true)
//                    .eq(StoreBrand::getType, BrandTypeEnum.XUNWU)
//                    .in(StoreBrand::getId, brandIdList)
//                    .orderByAsc(StoreBrand::getLetter)
//            );
//            if (CollectionUtils.isNotEmpty(list)) {
//                voList = list.stream().map(brand -> new BrandVo(brand.getId(), brand.getEnName(), brand.getLetter()))
//                        .sorted((x, y) -> {
//                            String brandNameX = x.getName();
//                            String brandNameY = y.getName();
//                            //小写转大写
//                            if (brandNameX.matches(".*?[a-z]+.*?")){
//                                brandNameX = brandNameX.toUpperCase();
//                            }
//                            if (brandNameY.matches(".*?[a-z]+.*?")){
//                                brandNameY = brandNameY.toUpperCase();
//                            }
//                            return brandNameX.compareTo(brandNameY);
//                        }).collect(Collectors.toList());
//
//                redisUtil.set(REDIS_KEY_BRANDLIST, voList, ExpireTimeConstants.HALF_HOUR, TimeUnit.SECONDS);
//            } else {
//                voList = new ArrayList<>();
//            }
//        }
//        return voList;
    }
}
